package com.daj.dao;

import com.daj.pojo.Team;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;


/**
 * @ Since :  1.0
 * @ Author:  DAJ
 * @ Date  :  20:17 2021/6/27
 */
public class TeamDao extends JdbcDaoSupport {



    public int insert(Team team){
        String sql = "insert into team (tname,location) values(?,?)";
        return this.getJdbcTemplate().update(sql,team.getTname(),team.getLocation());
    }

    public int update(Team team){
        String sql = "update team set tname=?,location=? where tid=?";
        return this.getJdbcTemplate().update(sql,team.getTname(),team.getLocation(),team.getTid());
    }

    public int del(int id){
        String sql = "delete from team where tid=?";
        return this.getJdbcTemplate().update(sql,id);
    }

    /**
     * 自己封装一个处理结果的方法
     * @param resultSet
     * @return
     * @throws SQLException
     */
    public Team handResult(ResultSet resultSet) throws SQLException {
        Team team = new Team();
        team.setTid(resultSet.getInt("tid"));
        team.setTname(resultSet.getString("tname"));
        team.setLocation(resultSet.getString("location"));
        return team;
    }

    public Team findById(int id){
        String sql = "select * from team where tid=?";
        return this.getJdbcTemplate().queryForObject(sql, new Object[]{id}, new RowMapper<Team>() {
            @Override
            public Team mapRow(ResultSet resultSet, int i) throws SQLException {
                return handResult(resultSet);
            }
        });
    }

    public List<Team> findAll(){
        String sql = "select * from team";
        return this.getJdbcTemplate().query(sql, new RowMapper<Team>() {

            @Override
            public Team mapRow(ResultSet resultSet, int i) throws SQLException {
                return handResult(resultSet);
            }
        });
    }

    public int getCount(){
        String sql = "select count(tid) from team";
        return this.getJdbcTemplate().queryForObject(sql,Integer.class);
    }

    public Map<String, Object> getMany(){
        String sql = "select max(tid),min(tid) from team";
        return this.getJdbcTemplate().queryForMap(sql);
    }

}
